const utils = require('../../utils/index.js')
const menu = require('../../utils/menu.js')
const {
session, encrypt, update,
page, page2, add, deleteData, mlist, generateAiPersonal
} = require("../../api/index")
Page({


/**
* 页面的初始数据
*/
data: {
avatarurl: "",
// 聊天
recordListIndex: 'i0',
recordList: [],
nowfid: 0,
nowfpic: '',
nowname: '',
nowtablename: '',
chatList: [],
chatForm: {
  content: ''
},
chatTimer: null,
hasChatList: [
  'chuangyezhe',
  'daoshi',
  'fuzeren',
  'xiangmuxinxi',
],
friendList: [],
myFriends: [], // 新增
friendRequests: [], // 新增
friendTab: 'myFriends', // 当前tab，myFriends或friendRequests
mypic: wx.getStorageSync('avatarurl'),
passWorded: "",
newPassword: '',
confirmPassword: '',
nickname: '',
token: '',
backMenuList: "",
userInfo: {},
secondIndex: false,
baseURL: wx.getStorageSync('baseURL') + '/',
orderList: [{
name: '全部',
icon: 'icon-dingdan1'
},
{
name: '未支付',
icon: 'icon-dingdan2'
},
{
name: '已支付',
icon: 'icon-dingdan3'
},
{
name: '已完成',
icon: 'icon-dingdan4'
},
{
name: '已取消',
icon: 'icon-dingdan5'
},
],
aipersonalCount: 0,
modules: [], // 新增，功能模块化数据
projectCount: 0,
resultCount: 0,
favCount: 0,
},

/**
* 生命周期函数--监听页面加载
*/

onLoad(options) {
this.setData({
nickname: wx.getStorageSync('nickname'),
avatarurl: wx.getStorageSync('avatarurl')
})
this.getData()
this.getAipersonalCount();

},
onShow() {
this.onLoad()
this.setData({
nickname: wx.getStorageSync('nickname'),
avatarurl: wx.getStorageSync('avatarurl'),
mypic: wx.getStorageSync('avatarurl')
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},

async getFriendList() {
    let res = await page('chatfriend', {
        uid: getApp().globalData.userInfo.id
    });
    // 只保留type==1（已通过）的记录
    let arr = res.data.list.filter(item => item.type == 1);
    // 用Set对fid+name+picture去重，只保留每个fid+name+picture的第一条
    const seen = new Set();
    const uniqueArr = [];
    for (const item of arr) {
        const key = item.fid + '|' + (item.name || '') + '|' + (item.picture || '');
        if (!seen.has(key)) {
            uniqueArr.push(item);
            seen.add(key);
        }
    }
    // 实时查每个好友的最新头像
    const baseURL = wx.getStorageSync('baseURL');
    for (let item of uniqueArr) {
        await new Promise((resolve) => {
            wx.request({
                url: baseURL + '/chuangyezhe/query',
                method: 'GET',
                data: { id: item.fid },
                success: (res) => {
                    if (res.data && res.data.code === 0 && res.data.data && res.data.data.touxiang) {
                        item.picture = res.data.data.touxiang;
                        resolve();
                        return;
                    }
                    // 查导师
                    wx.request({
                        url: baseURL + '/daoshi/query',
                        method: 'GET',
                        data: { id: item.fid },
                        success: (res2) => {
                            if (res2.data && res2.data.code === 0 && res2.data.data && res2.data.data.touxiang) {
                                item.picture = res2.data.data.touxiang;
                                resolve();
                                return;
                            }
                            // 查负责人
                            wx.request({
                                url: baseURL + '/fuzeren/query',
                                method: 'GET',
                                data: { id: item.fid },
                                success: (res3) => {
                                    if (res3.data && res3.data.code === 0 && res3.data.data && res3.data.data.touxiang) {
                                        item.picture = res3.data.data.touxiang;
                                    }
                                    resolve();
                                },
                                fail: resolve
                            });
                        },
                        fail: resolve
                    });
                },
                fail: resolve
            });
        });
    }
    uniqueArr.forEach(item => {
        if (!item.picture) {
            item.picture = '/static/upload.png';
        }
    });
    this.setData({
        friendList: uniqueArr
    });
    const compFriend = this.selectComponent('#firendFrame');
    if (compFriend) compFriend.showFrame();
},
async confirmFriend(e) {
const item = e.currentTarget.dataset.item;
let _this = this.data;
let _that = this;
wx.showModal({
title: '提示',
content: '是否同意好友申请？',
success: async function (obj) {
if (obj.confirm) {
await add('chatfriend', {
    uid: item.fid,
    fid: _this.userInfo.id,
    type: 1,
    tablename: wx.getStorageSync("nowTable"),
    name: wx.getStorageSync("nickname"),
    picture: _this.mypic,
})
await add('chatfriend', {
    fid: item.fid,
    uid: _this.userInfo.id,
    type: 1,
    tablename: item.tablename,
    name: item.name,
    picture: item.picture
})
await deleteData('chatfriend', [item.id])
_that.getFriendList()

wx.showToast({
    title: '添加好友成功',
    icon: 'none'
})
}
}
})

},
cancelFirendFrame() {
this.selectComponent('#firendFrame').hideFrame()
},
changeHasChat() {
let table = wx.getStorageSync("nowTable")
for (let x in this.data.hasChatList) {
if (this.data.hasChatList[x] == table) {
return true
}
}
return false
},
async getData() {
this.setData({
token: wx.getStorageSync('token'),
})
if (!this.data.token) {
return
}
let table = wx.getStorageSync("nowTable");
let res
if(table){
res = await session(table)
}
const menus = menu.default.list()
for (let x in menus) {
if (menus[x].tableName == table) {
let backMenulist = menus[x].backMenu;
this.setData({
backMenuList: backMenulist
})
break
}
}
res.data["touxiang"] = res?.data?.touxiang?.replace('upload', 'file')
// 新增：根据角色设置displayName和displayId
if(table === 'daoshi') {
  res.data.displayName = res.data.daoshixingming;
  res.data.displayId = res.data.daoshigonghao;
} else if(table === 'chuangyezhe') {
  res.data.displayName = res.data.xueshengxingming;
  res.data.displayId = res.data.xuehao;
} else {
  res.data.displayName = res.data.xueshengxingming || res.data.daoshixingming;
  res.data.displayId = res.data.xuehao || res.data.daoshigonghao;
}
// 新增：确保tableName字段存在
res.data.tableName = table;
this.setData({
userInfo: res.data
})
getApp().globalData.userInfo = res.data
wx.setStorageSync('userInfo', res.data);

// 新增：功能模块化
this.setData({ modules: this.buildModules(res.data, this.data.backMenuList) });

// 获取项目、成果、收藏数量
this.getSummaryCounts(res.data);
},

/**
 * 获取项目、成果、收藏数量
 */
getSummaryCounts(userInfo) {
  const token = wx.getStorageSync('token');
  const baseURL = wx.getStorageSync('baseURL');
  const xuehao = userInfo.xuehao;
  // 项目数量（项目信息管理）
  wx.request({
    url: baseURL + '/xiangmuxinxi/page',
    method: 'GET',
    data: { page: 1, limit: 1, fuzerenzhanghao: xuehao },
    header: { 'Token': token || '' },
    success: (res) => {
      let count = 0;
      if (res.data && res.data.code === 0) {
        if (typeof res.data.total === 'number') count = res.data.total;
        else if (res.data.data && typeof res.data.data.total === 'number') count = res.data.data.total;
      }
      this.setData({ projectCount: count });
    }
  });
  // 成果数量（创新成果管理）
  wx.request({
    url: baseURL + '/xiangmuchengguo/page',
    method: 'POST',
    data: { page: 1, limit: 1, xuehao },
    header: { 'Token': token || '' },
    success: (res) => {
      let count = 0;
      if (res.data && res.data.code === 0) {
        if (typeof res.data.total === 'number') count = res.data.total;
        else if (res.data.data && typeof res.data.data.total === 'number') count = res.data.data.total;
      }
      this.setData({ resultCount: count });
    }
  });
  // 收藏数量（我的收藏管理）
  wx.request({
    url: baseURL + '/storeup/page',
    method: 'GET',
    data: { page: 1, limit: 1, xuehao },
    header: { 'Token': token || '' },
    success: (res) => {
      let count = 0;
      if (res.data && res.data.code === 0) {
        if (typeof res.data.total === 'number') count = res.data.total;
        else if (res.data.data && typeof res.data.data.total === 'number') count = res.data.data.total;
      }
      this.setData({ favCount: count });
    }
  });
},
/**
 * 构建功能模块（创业者/导师分组）
 */
buildModules(userInfo, backMenuList) {
  const isChuangyezhe = userInfo.tableName === 'chuangyezhe';
  const isDaoshi = userInfo.tableName === 'daoshi';
  // 静态icon映射（可根据实际需求调整icon路径）
  const iconMap = {
    '密码修改': '/static/images/mima.png',
    '好友列表': '/static/images/tianjiahaoyou.png',
    '我的收藏': '/static/images/shoucang.png',
    '我的发布': '/static/images/fenxiang.png',
    '论坛管理': '/static/images/gonggao.png',
    '学生列表': '/static/images/yonghu.png',
    '评审管理': '/static/images/chakan.png',
    '创新成果': '/static/images/biaozhang.png',
    '项目库': '/static/images/xiangmuku.png',
    '导师推荐': '/static/images/daoshituijian.png',
    '电子档案': '/static/images/dianzidangan.png',
    '城市': '/static/images/chengshi.png',
    '邮箱': '/static/images/youxiang.png',
    '项目成果': '/static/images/xiangmuchengguo.png',
    '退出登录': '/static/images/shezhi.png',
    // ...可继续补充
  };
  // 我的管理/学生管理模块icon fallback
  const getMenuIcon = menuName => iconMap[menuName] || '/static/images/shoucang.png';
  // 需要过滤的菜单名
  const filterMenus = [
    '邀请信息管理',
    '知识产权管理',
    '创业大赛管理',
    '创业活动管理'
  ];
  // 创业者模块
  if (isChuangyezhe) {
    const modules = [
      {
        title: '我的管理',
        items: (backMenuList || []).filter(item => filterMenus.indexOf(item.menu) === -1).map(item => {
          // 修正创新成果管理的tableName
          if (item.menu === '创新成果管理') {
            item.tableName = 'chuangxinchengguo';
            if (item.child && item.child[0]) {
              item.child[0].tableName = 'chuangxinchengguo';
            }
          }
          // 修正项目信息管理的tableName
          if (item.menu === '项目信息管理') {
            item.tableName = 'xiangmuxinxi';
            if (item.child && item.child[0]) {
              item.child[0].tableName = 'xiangmuxinxi';
            }
          }
          if (item.menu === '我的收藏管理') {
            item.tableName = 'storeup';
            if (item.child && item.child[0]) {
              item.child[0].tableName = 'storeup';
            }
          }
          return {
            name: item.menu,
            icon: getMenuIcon(item.menu),
            action: 'menuTap',
            raw: item
          }
        })
      },
      {
        title: '账号安全',
        items: [
          { name: '密码修改', icon: iconMap['密码修改'], action: 'uppdatePassword' },
        ]
      },
      {
        title: '我的社交',
        items: [
          { name: '好友列表', icon: iconMap['好友列表'], action: 'goFriendManage' },
        ]
      },
      {
        title: '其他',
        items: [
          { name: '退出登录', icon: iconMap['退出登录'], action: 'logout' },
        ]
      }
    ];
    return modules;
  }
  // 导师模块
  if (isDaoshi) {
    const modules = [
      {
        title: '学生管理',
        items: (backMenuList || []).map(item => ({
          name: item.menu,
          icon: iconMap[item.menu] || '/static/center/default.png',
          action: 'menuTap',
          raw: item
        }))
      },
      {
        title: '账号安全',
        items: [
          { name: '密码修改', icon: iconMap['密码修改'], action: 'uppdatePassword' },
        ]
      },
      {
        title: '我的社交',
        items: [
          { name: '好友列表', icon: iconMap['好友列表'], action: 'goFriendManage' },
        ]
      },
      {
        title: '其他',
        items: [
          { name: '退出登录', icon: iconMap['退出登录'], action: 'logout' },
        ]
      }
    ];
    return modules;
  }
  // 默认
  return [];
},
userRecharge() {
wx.removeStorageSync('payObject');
wx.navigateTo({
url: "/pages/shop-recharge/pay-confirm"
})
},
menuTap(e) {
  const item = e.currentTarget.dataset.item;
  let tableName = item.tableName;
  if (!tableName && item.child && item.child[0]) {
    tableName = item.child[0].tableName;
  }
  if (!tableName) {
    wx.showToast({ title: '菜单配置错误', icon: 'none' });
    return;
  }
  // 直接跳转，便于调试
  let path = '';
  if (tableName === 'chuangxinchengguo') {
    path = '/pages/chuangxinchengguo/chuangxinchengguo';
  } else if (tableName === 'storeup') {
    path = '/pages/storeup/list';
  } else if (tableName === 'xiangmushenqing') {
    path = '/pages/xiangmushenqing/list';
  } else if (tableName === 'xiangmuxinxi') {
    path = '/pages/xiangmuxinxiguanli/xiangmuxinxiguanli';
  } else {
    path = `/pages/${tableName}/${tableName}-list`;
  }
  wx.navigateTo({
    url: path,
    fail: (err) => {
      wx.showToast({ title: '跳转失败', icon: 'none' });
      console.error('跳转失败', path, err);
    }
  });
},
tologin() {
wx.navigateTo({
url: '/pages/login/login',
})
},
optionsTap(e) {
// 论坛管理
const item = e.currentTarget.dataset.item;
const tableName = item.tableName
if (item.menu.includes("论坛交流")) {
wx.navigateTo({
url: `/pages/${tableName}/${tableName}-my`,
})
} else if (item.menu.includes("我的发布")) {
wx.navigateTo({
url: `/pages/${tableName}/${tableName}-add-or-update`,
})

}

},

uppdatePassword() {
wx.navigateTo({
    url: '/pages/change-password/change-password'
});
},

onPageTap() {
wx.navigateTo({
url: "/pages/shop-recharge/buyvip-confirm"
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {

},

/**
* 生命周期函数--监听页面卸载
*/
onUnload() {

},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {

},

/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {

},

/**
* 用户点击右上角分享
*/
onShareAppMessage() {

},

/**
* 生成电子档案
*/
onGenerateAiPersonal() {
  wx.navigateTo({
    url: '/pages/aipersonal/list'
  });
},
/**
 * 获取电子档案数量
 */
getAipersonalCount() {
  const token = wx.getStorageSync('token');
  const userInfo = wx.getStorageSync('userInfo');
  if (!userInfo || !userInfo.xuehao) {
    this.setData({ aipersonalCount: 0 });
    return;
  }
  const baseURL = wx.getStorageSync('baseURL');
  wx.request({
    url: baseURL + '/aipersonal/page',
    method: 'GET',
    data: {
      page: 1,
      limit: 1,
      sort: 'shengchengshijian',
      order: 'desc',
      xuehao: userInfo.xuehao // 只查当前用户的电子档案
    },
    header: {
      'Token': token || ''
    },
    success: (res) => {
      let count = 0;
      if (res.data && res.data.code === 0) {
        // 兼容不同后端返回结构
        if (typeof res.data.total === 'number') {
          count = res.data.total;
        } else if (res.data.data && typeof res.data.data.total === 'number') {
          count = res.data.data.total;
        }
      }
      this.setData({ aipersonalCount: count });
    },
    fail: () => {
      this.setData({ aipersonalCount: 0 });
    }
  });
},
async getRecordList(type = 1) {
  let res = await page2('/chatfriend', {uid: this.data.userInfo.id, type: 2})
  let recordList = res?.data?.list.map(v => {
    if (v.content?.includes('file/')) {
      v['isImg'] = true
    }
    return v
  })
  this.setData({
    recordList
  })
  const compRecord = this.selectComponent('#recordListFrame');
  if (compRecord) compRecord.showFrame();
},
cancelMyChatShow() {
  this.getRecordList()
  clearTimeout(this.data.chatTimer)
  const compChat2 = this.selectComponent('#myChatFrame');
  if (compChat2) compChat2.hideFrame();
},
async uploadSuccess() {
  let userInfo = getApp().globalData.userInfo
  clearTimeout(this.data.chatTimer)
  wx.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      let _this = this.data;
      // 上传网络图片
      wx.uploadFile({
        url: `${_this.baseURL}/file/upload`,
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          'Token': wx.getStorageSync('token')
        },
        success: async (uploadFileRes) => {
          let _this = this.data;
          let result = JSON.parse(uploadFileRes.data);
          // result.file是上传成功为网络图片的名称
          let res = await page('chatfriend', {
              uid: userInfo.id,
              fid: this.data.nowfid,
          })
          if (!res.data.list.length) {
              await page('chatfriend', {
                      uid: userInfo.id,
                      fid: this.data.nowfid,
                      name: wx.getStorageSync("nickname"),
                      picture: _this.mypic,
                      type: 2,
                      tablename: wx.getStorageSync("nowTable")
                  }
              )
              await page('chatfriend', {
                  fid: userInfo.id,
                  uid: _this.fid,
                  name: wx.getStorageSync("nickname"),
                  picture: _this.mpic,
                  type: 2,
                  tablename: wx.getStorageSync("nowTable")
              })
          }
          await add('chatmessage', {
              uid: userInfo.id,
              fid: _this.nowfid,
              content: 'file/' + result.file,
              format: 2
          })
          _this.chatForm = {
              content: ''
          }
          this.getChatList()
        }
      })
    }
  })
},
async getChatList() {
  let res = await mlist('chatmessage', {
    page: 1,
    limit: 1000,
    uid: this.data.userInfo.id,
    fid: this.data.nowfid
  })
  let chatList = res?.data?.list.map(v => {
    if (v.format == 2) {
      v.content = v.content.replace('upload', 'file')
    }
    return v
  }) || [];
  // 批量查头像
  for (let msg of chatList) {
    // 本人消息
    if (msg.uid === this.data.userInfo.id) {
      msg.picture = this.data.userInfo.touxiang;
      msg.tableName = this.data.userInfo.tableName;
      msg.displayName = this.data.userInfo.displayName;
      msg.displayId = this.data.userInfo.displayId;
      msg.chengshi = this.data.userInfo.chengshi;
      msg.zhuanye = this.data.userInfo.zhuanye;
      continue;
    }
    // 对方消息，尝试查创业者/导师/负责人
    const baseURL = wx.getStorageSync('baseURL');
    await new Promise((resolve) => {
      wx.request({
        url: baseURL + '/chuangyezhe/query',
        method: 'GET',
        data: { id: msg.uid },
        success: (res) => {
          if (res.data && res.data.code === 0 && res.data.data && res.data.data.touxiang) {
            msg.picture = res.data.data.touxiang;
            msg.tableName = 'chuangyezhe';
            msg.displayName = res.data.data.xueshengxingming;
            msg.displayId = res.data.data.xuehao;
            msg.chengshi = res.data.data.chengshi;
            msg.zhuanye = res.data.data.zhuanye;
            resolve();
            return;
          }
          // 查导师
          wx.request({
            url: baseURL + '/daoshi/query',
            method: 'GET',
            data: { id: msg.uid },
            success: (res2) => {
              if (res2.data && res2.data.code === 0 && res2.data.data && res2.data.data.touxiang) {
                msg.picture = res2.data.data.touxiang;
                msg.tableName = 'daoshi';
                msg.displayName = res2.data.data.daoshixingming;
                msg.displayId = res2.data.data.daoshigonghao;
                msg.chengshi = res2.data.data.chengshi;
                msg.zhuanye = res2.data.data.zhuanye;
                resolve();
                return;
              }
              // 查负责人
              wx.request({
                url: baseURL + '/fuzeren/query',
                method: 'GET',
                data: { id: msg.uid },
                success: (res3) => {
                  if (res3.data && res3.data.code === 0 && res3.data.data && res3.data.data.touxiang) {
                    msg.picture = res3.data.data.touxiang;
                    msg.tableName = 'fuzeren';
                    msg.displayName = res3.data.data.fuzerenxingming;
                    msg.displayId = res3.data.data.fuzerenzhanghao;
                    msg.chengshi = res3.data.data.chengshi;
                    msg.zhuanye = res3.data.data.zhuanye;
                  }
                  resolve();
                },
                fail: resolve
              });
            },
            fail: resolve
          });
        },
        fail: resolve
      });
    });
  }
  this.setData({
    chatList
  })
  setTimeout(() => {
    this.setData({
      recordListIndex: 'i' + (chatList.length - 1)
    })
  }, 0)
  this.setData({
    chatTimer: setTimeout(() => {
      this.getChatList()
    }, 5000)
  })
},
async chatClick(e) {
  const row = e.currentTarget.dataset.item;
  if (row.type == 0) {
    return
  }
  let obj = {}
  obj['nowfid'] = row.fid;
  obj['nowfpic'] = row.picture; // 直接用好友列表头像
  obj['nowname'] = row.name;
  obj['nowtablename'] = row.tablename;
  this.setData(obj)
  await this.getChatList()
  const compChat = this.selectComponent('#myChatFrame');
  if (compChat) compChat.showFrame();
},
cancelrecordListFrame() {
  const compRecord2 = this.selectComponent('#recordListFrame');
  if (compRecord2) compRecord2.hideFrame();
},
contentTap(e) {
  let chatForm = Object.assign(this.data.chatForm, {})
  chatForm['content'] = e.detail.value;
  this.setData(chatForm)
},
async addChat() {
  let userInfo = getApp().globalData.userInfo;
  clearTimeout(this.data.chatTimer)
  if (!this.data.chatForm.content) {
    return
  }
  let res = await page('chatfriend', {
    uid: userInfo.id,
    fid: this.data.nowfid,
    type: 2
  })
  if (!res.data.list.length) {
    await add('chatfriend', {
      uid: userInfo.id,
      fid: this.data.nowfid,
      name: this.data.nowname,
      picture: this.data.nowfpic,
      type: 2,
      tablename: 'yonghu'
    })
    await add('chatfriend', {
      fid: userInfo.id,
      uid: this.data.nowfid,
      name: wx.getStorageSync("nickname"),
      picture: this.data.mypic,
      type: 2,
      tablename: wx.getStorageSync("nowTable")
    })
  }
  await add('chatmessage', {
    fid: this.data.nowfid,
    uid: userInfo.id,
    content: this.data.chatForm.content,
    format: 1
  })
  this.setData({
    chatForm: {
      content: ''
    }
  })
  this.getChatList()
},
toDetail() {
  wx.navigateTo({
    url: '/pages/user-info/user-info'
  })
},
  onShowProfileCard(e) {
    const item = e.currentTarget.dataset.item;
    // 优先用item本身信息判断
    if (item && item.tableName === 'chuangyezhe') {
      // 优先用item.picture作为头像
      let touxiang = item.picture || item.touxiang;
      this.setData({
        showProfileCard: true,
        profileCardUser: { ...item, touxiang }
      });
      return;
    }
    // 如果没有tableName，尝试通过fid查创业者信息
    const fid = item && (item.fid || item.uid);
    if (!fid) return;
    const baseURL = wx.getStorageSync('baseURL');
    wx.request({
      url: baseURL + '/chuangyezhe/query',
      method: 'GET',
      data: { id: fid },
      success: (res) => {
        if (res.data && res.data.code === 0 && res.data.data && (res.data.data.tableName === 'chuangyezhe' || res.data.data.xuehao)) {
          // 查到创业者，头像优先用item.picture
          let touxiang = item.picture || res.data.data.touxiang;
          this.setData({
            showProfileCard: true,
            profileCardUser: { ...res.data.data, touxiang }
          });
        } else {
          wx.showToast({ title: '该用户不是创业者', icon: 'none' });
        }
      }
    });
  },
  onHideProfileCard() {
    this.setData({ showProfileCard: false });
  },
  stopPropagation() {},
  onProfileCardAIPersonal(e) {
    // 用profileCardUser查电子档案
    const user = this.data.profileCardUser;
    const xuehao = user.displayId || user.xuehao;
    if (!xuehao) {
      wx.showToast({ title: '未获取到学号', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '查询中...' });
    const baseURL = wx.getStorageSync('baseURL');
    wx.request({
      url: baseURL + '/aipersonal/page',
      method: 'GET',
      data: {
        page: 1,
        limit: 1,
        sort: 'shengchengshijian',
        order: 'desc',
        xuehao: xuehao
      },
      success(res) {
        wx.hideLoading();
        if (res.data && res.data.code === 0 && res.data.data && res.data.data.list && res.data.data.list.length > 0) {
          wx.navigateTo({
            url: `/pages/aipersonal/list?xuehao=${xuehao}`
          });
        } else {
          wx.showToast({ title: '该用户没有生成电子档案', icon: 'none' });
        }
      },
      fail() {
        wx.hideLoading();
        wx.showToast({ title: '查询失败', icon: 'none' });
      }
    });
  },
  onProfileTap() {
    wx.navigateTo({
      url: '/pages/user-info/user-info',
    });
  },
  // tab切换
  onFriendTabChange(e) {
    this.setData({ friendTab: e.currentTarget.dataset.tab });
  },
  goFriendManage() {
    wx.navigateTo({
      url: '/pages/friend-manage/friend-manage'
    })
  },
  onModuleTap(e) {
    const item = e.currentTarget.dataset.item;
    if (!item) return;
    if (item.action === 'uppdatePassword') {
      this.uppdatePassword();
    } else if (item.action === 'goFriendManage') {
      this.goFriendManage();
    } else if (item.action === 'menuTap') {
      // 传递原始菜单数据
      this.menuTap({ currentTarget: { dataset: { item: item.raw } } });
    } else if (item.action === 'logout') {
      wx.removeStorageSync('token');
      wx.removeStorageSync('userInfo');
      wx.navigateTo({ url: '/pages/login/login' });
    }
  },
})